<!--
 * @author hugh
 * @time  2021-01-10 11:40
 * @title  用户管理
 * @desc
 -->
<template>
  <div class="about">
    <el-form :inline="true" :model="seekForm" class="header-from align-center">
      <el-form-item label="用户名">
        <el-input size="mini" v-model="seekForm.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input size="mini" v-model="seekForm.mobile" placeholder="请输入电话号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="success" @click="onSubmit">查询</el-button>
        <el-button icon="el-icon-edit" size="mini" type="warning" @click="whiteRow('AddFromModal',-1, tableData)">添加</el-button>
        <!-- <el-button @click="handleDownload" type="primary">导出</el-button> -->
      </el-form-item>
    </el-form>

    <el-card :body-style="{padding: '0px'}">
      <el-table v-loading="fullscreenLoading" border size="mini" :data="tableData" class="table-box" :height="tableHeight">
        <el-table-column label="序号" width="100">
          <template #default="scope">
            {{scope.$index+1}}
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="用户ID" width="80">
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="100">
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" width="180">
        </el-table-column>
        <el-table-column label="头像" width="100">
          <template #default="scope">
            <img v-if="scope.row.avatar" class="image-sm round" :src="scope.row.avatar" />
          </template>
        </el-table-column>
        <el-table-column prop="countryCode" label="国家码" width="80">
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-popover placement="bottom" :width="100" trigger="click">
              <template #reference>
                <el-tag size="mini" v-if="scope.row.status==='auditing'" type="warning" effect="dark">待审核</el-tag>
                <el-tag size="mini" v-else-if="scope.row.status==='normal'" type="success" effect="dark">正常</el-tag>
                <el-tag size="mini" v-else-if="scope.row.status==='closed'" type="info" effect="dark">禁用</el-tag>
                <el-tag size="mini" v-else type="danger" effect="dark">注销</el-tag>
              </template>
              <el-radio-group style="text-align: left;" v-model="scope.row.status" @change="onUpdataStatus(scope.row.userId,$event)">
                <el-radio style="width: 100%;margin-left: 0;" class="margin-top-sm" v-for="item in statusList" :key="item.value"
                  :label="item.value" border>{{item.label}}</el-radio>
              </el-radio-group>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
        </el-table-column>
        <el-table-column prop="status" label="操作" min-width="340" fixed="right">
          <template #default="scope">
            <el-button type="danger" size="mini" @click.native.prevent="deleteRow(scope.$index,scope.row.userId,tableData)">删除</el-button>
            <el-button type="primary" size="mini" @click.native.prevent="whiteRow('UpdataFromModal',scope.$index,scope.row)">编辑</el-button>
            <el-button type="success" size="mini" @click.native.prevent="whiteRow('RoleModal',scope.$index,scope.row)">用户角色</el-button>
            <el-button type="warning" size="mini" @click.native.prevent="whiteRow('PwdModal',scope.$index,scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="padding-sm">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" v-model:currentPage="currentPage"
          layout="prev, pager, next" :page-count="total" :page-size="size">
        </el-pagination>
      </div>
    </el-card>
    <el-dialog :title="dialogModal==='AddFromModal'?'添加用户':'编辑用户'" :model-value="dialogModal==='AddFromModal'||dialogModal==='UpdataFromModal'"
      @close="hideDialog">
      <el-form :model="formData" :rules="rules" ref="ruleFormDataRef">
        <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
          <el-input v-model="formData.username" autocomplete="off" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile" :label-width="formLabelWidth">
          <el-input v-model="formData.mobile" autocomplete="off" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="avatar" :label-width="formLabelWidth" @click="AvatarsModal=true">
          <el-input v-model="formData.avatar" autocomplete="off" placeholder="请输入头像链接"></el-input>
        </el-form-item>
        <!--   <el-form-item label="地址" :label-width="formLabelWidth">
          <el-cascader placeholder="请选择地址" :options="options" clearable @change="onSelectAddress"></el-cascader>
        </el-form-item> -->
        <el-form-item label="选择国家" :label-width="formLabelWidth">
          <el-select v-model="formData.countryCode" placeholder="请选择">
            <el-option v-for="item in countryList" :key="item.code" :label="item.name" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm('ruleFormDataRef')">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleFormDataRef')">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <dialog-from title="重置密码" :formData="ruleForm" :rules="rules" fromRef="ruleFormRef" :show="dialogModal" tag="PwdModal"
      @onhide="hideDialog" @onchange="onChangeDialog">
      <template v-slot:content="scope">
        <el-form-item label="账户密码" prop="pwd" :label-width="formLabelWidth">
          <el-input v-model="ruleForm.pwd" type="password" autocomplete="off" placeholder="请输入账户密码" :minlength="6"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="resetpwd" :label-width="formLabelWidth">
          <el-input v-model="ruleForm.resetpwd" type="password" autocomplete="off" placeholder="请第二次输入密码" :minlength="6"></el-input>
        </el-form-item>
      </template>
    </dialog-from>
    <el-dialog title="角色选择" :model-value="dialogModal==='RoleModal'" @close="dialogModal = null">
      <el-form ref="ruleFromRef">
        <el-form-item label="选择角色" :label-width="formLabelWidth">
          <template v-for="(item,index) in rolesList" :key="index">
            <div>
              <el-checkbox v-model="item.checked" @change="handleCheckAllChange(index,$event)">{{item.clientName}}</el-checkbox>
              <div class="margin-left-sm">
                <el-checkbox-group v-model="item.current" :max="1">
                  <el-checkbox v-for="(child,cindex) in item.roles" :label="child.roleId" :key="cindex" @change="handleRadioChange(index,child.roleId,$event)">{{child.name}}</el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="hideDialog">取 消</el-button>
          <el-button type="primary" @click="onChangeDialog">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="选择头像" v-model="AvatarsModal">
      <uploader @onchange="onSelectAvatar"></uploader>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  toRefs,
  reactive,
  getCurrentInstance,
  watch,
  ref
} from 'vue'
import {
  useRouter
} from 'vue-router'

import {
  fromPwd,
  fromLength,
  fromPhone
} from '@/common/from_role'
import {
  useStore
} from 'vuex'
import {
  formatJson
} from '@/utils'
import {
  exportJson2Excel
} from '@/utils/excel'
import DialogFrom from '@/components/DialogFrom.vue'
import Uploader from '@/components/Uploader.vue'
export default defineComponent({
  name: 'user',
  components: {
    DialogFrom,
    Uploader
  },
  setup() {
    // 路由
    const router = useRouter()
    // vuex
    const store = useStore()
    // 绑定挂载全局对象
    const {
      proxy
    } = getCurrentInstance() as any

    const {
      userList,
      userAdd,
      userUpdata,
      userDel,
      userPwdReset,
      userUpdataStatus,
      userRoleList,
      userRoleUpdate
    } = proxy.$api.User
    const {

      countryList
    } = proxy.$api.Other
    // const ruleFormRef = ref(null);
    // const ruleFormDataRef:Refs<Elform|null> = ref(null);
    const baseFrom: any = {
      avatar: '',
      countryCode: 86,
      mobile: '',
      roleIds: [],
      userId: 0,
      username: '',
      address: '',
      status: 'normal',
      clientId: store.state.clientId,
      createTime: 0
    }

    // 定义参数集合
    const data = reactive({
      tableHeight: store.state.tableHeight,
      downloadLoading: false,
      options: [],
      listLoading: false,
      total: 100,
      size: 20,
      currentPage: 1,
      tableData: [baseFrom],
      dialogModal: '',
      seekForm: {
        mobile: '',
        username: ''
      },
      formData: baseFrom,
      formLabelWidth: '120px',
      statusList: [{
        value: 'auditing',
        label: '待审核'
      }, {
        value: 'normal',
        label: '正常'
      }, {
        value: 'closed',
        label: '禁用'
      }],
      rolesList: [{
        clientId: 0,
        clientName: 0,
        checked: false,
        current: [0],
        roles: [{
          administrator: true,
          checked: true,
          clientId: 0,
          code: '',
          name: '',
          roleId: 0
        }]
      }],
      roleIds: [0],
      ruleForm: {
        resetpwd: '',
        pwd: ''
      },
      rules: {
        resetpwd: fromPwd('请重复输入密码'),
        pwd: fromPwd('请输入新密码'),
        username: fromLength('请输入用户名'),
        mobile: fromPhone('请输入用户手机号')
      },
      isIndeterminate: true,
      fullscreenLoading: false,
      AvatarsModal: false,
      countryList: [{
        code: 86,
        name: '中国',
        nameEn: 'China',
        nameTraditional: '中國'
      }]
    })
    /**
       * 路由跳转
       */
    function toRouter(path: string) {
      router.push(path)
    }
    /**
       * 导出表格示例
       */
    function handleDownload() {
      data.downloadLoading = true
      const tHeader = ['Id', 'Username', 'mobile', 'avatar', 'roleIds']
      const filterVal = ['id', 'username', 'mobile', 'avatar', 'roleIds']
      const fromData = formatJson(filterVal, data.tableData)
      exportJson2Excel(tHeader, fromData, 'User', undefined, undefined, true, 'xlsx')
      data.downloadLoading = false
    }

    /**
       * 选择地址
       */
    function onSelectAddress(res: any) {
      const address = res[0] + res[1] + res[2]
      data.formData.address = address
    }
    /**
       * 编写行
       */
    function whiteRow(modal: string, index: number, item: any) {
      if (index > -1) {
        for (const key in item) {
          data.formData[key] = item[key]
        }
        console.log(data.formData)
      } else {
        hideDialog()
      }
      if (modal === 'RoleModal') {
        getRoleList()
      } else if (modal === 'PwdModal') {
        resetPwd()
      } else {
        data.dialogModal = modal
      }
    }
    /**
       * 添加行
       */
    function onAddRow(param: any) {
      userAdd(param).then((res: any) => {
        hideDialog()
        getDataList()
        proxy.$dialog('创建成功，初始密码为:' + res.password).then(() => {

        })
      }).catch((err: any) => {
        console.log(err)
      })
    }
    /**
       * 更新行
       */
    function onUpdataRow(param: any) {
      userUpdata(param).then((res: any) => {
        getDataList()
        hideDialog()
      }).catch((err: any) => {
        console.log(err)
      })
    }

    function onUpdataStatus(userId: any, status: any) {
      userUpdataStatus({
        userId: userId,
        status: status
      }).then((res: any) => {
        proxy.$msg('更新成功', 1)
        getDataList()
        // data.tableData[data.current] = data.formData;
      }).catch((err: any) => {
        console.log(err)
        proxy.$msg('更新失败', 0)
      })
    }
    /**
       * 删除用户
       */
    function deleteRow(index: number, userId: number, lists: any) {
      proxy.$dialog('是否删除该条数据?').then(() => {
        userDel({
          userId: userId
        }).then((res: any) => {
          proxy.$msg('删除成功', 1)
          getDataList()
          // lists.splice(index, 1);
        }).catch((err: any) => {
          proxy.$msg('删除失败', 0)
        })
      })
    }
    /**
       * 重置密码
       */
    function resetPwd() {
      // if (data.ruleForm.pwd !== data.ruleForm.resetpwd) {
      //   proxy.$msg("两次密码不相同，请检查后重新输入", 0);
      //   return;
      // }

      proxy.$dialog('是否重置用户密码?').then(() => {
        userPwdReset({
          userId: data.formData.userId
        }).then((res: any) => {
          // proxy.$msg("重置成功", 1);
          hideDialog()
          data.fullscreenLoading = true
          setTimeout(() => {
            data.fullscreenLoading = false
            proxy.$dialog('重置成功，重置密码为:' + res.password).then(() => {
              getDataList()
            })
          }, 1500)
        }).catch((err: any) => {
          console.log(err)
          proxy.$msg('重置失败', 0)
        })
      })
    }
    /**
       * 获取角色列表
       */
    function getRoleList() {
      data.roleIds = []
      userRoleList({
        userId: data.formData.userId
      }).then((res: any) => {
        const tablist = res
        for (let i = 0, len = tablist.length; i < len; i++) {
          tablist[i].current = []
          tablist[i].checked = false
          for (let j = 0, len = tablist[i].roles.length; j < len; j++) {
            if (tablist[i].roles[j].checked) {
              tablist[i].current = [tablist[i].roles[j].roleId]
              tablist[i].checked = true
              // data.roleIds[i] = tablist[i].roles[j].roleId;
              data.roleIds.push(tablist[i].roles[j].roleId)
            }
          }
        }
        data.rolesList = tablist
        data.dialogModal = 'RoleModal'
      }).catch((err: any) => {
        console.log(err)
      })
    }
    /**
       * 选择用户角色
       */
    function handleRadioChange(index: number, id: number, status: boolean) {
      data.rolesList[index].checked = status
      if (status) {
        if (data.roleIds.indexOf(id) === -1) {
          data.roleIds.push(id)
        }
        data.rolesList[index].current = [id]
      } else {
        data.rolesList[index].current = []
        const current = data.roleIds.indexOf(id)
        if (current !== -1) {
          data.roleIds.splice(current, 1)
        }
      }
    }
    /**
       * 设置用户角色
       */
    function onRoleUpdate() {
      if (data.roleIds.length == 0) {
        proxy.$msg('请至少给用户选择一个角色', 0)
        return
      }
      userRoleUpdate({
        roleIds: data.roleIds,
        userId: data.formData.userId
      }).then((res: any) => {
        proxy.$msg('设置成功', 1)
        hideDialog()
      }).catch((err: any) => {
        console.log(err)
        proxy.$msg('设置失败', 0)
      })
    }

    function handleSizeChange(val: number) {
      console.log(`每页 ${val} 条`)
    }

    function handleCurrentChange(val: number) {
      data.currentPage = val
      getDataList()
    }

    function onSubmit() {
      getDataList()
      console.log('submit!')
    }
    /**
       * 获取数据列表
       */
    function getDataList() {
      userList({
        clientId: data.formData.clientId,
        page: data.currentPage,
        size: data.size,
        mobile: data.seekForm.mobile,
        username: data.seekForm.username
      }).then((res: any) => {
        console.log(res)
        data.listLoading = false
        if (res.records && res.records.length > 0) {
          data.tableData = res.records
          data.total = res.pages
        } else {
          data.tableData = []
          data.total = 100
        }
      }).catch((err: any) => {
        console.log(err)
      })
    }
    /**
       * 获取省市区地址
       */
    function getAddressList() {
      countryList().then((res: any) => {
        console.log(res)
        data.countryList = res
      }).catch((err: any) => {
        console.log(err)
      })
    }

    /**
       * 选择权限
       */
    function onSelectRole(vals: any) {
      data.formData.roleIds = vals
      console.log(vals)
    }
    /**
       * 选择应用
       */
    function onChangeApp(id: number) {
      data.formData.clientId = id
      getDataList()
    }
    /**
       * 对话框统一响应
       */
    function onChangeDialog() {
      if (data.dialogModal === 'AddFromModal') {
        onAddRow((data.formData as any))
      } else if (data.dialogModal === 'UpdataFromModal') {
        onUpdataRow((data.formData as any))
      } else if (data.dialogModal === 'PwdModal') {
        resetPwd()
      } else if (data.dialogModal === 'RoleModal') {
        onRoleUpdate()
      }
    }
    /**
       * 关闭对话框
       */
    function hideDialog() {
      data.dialogModal = ''
      data.formData = {
        avatar: '',
        countryCode: 86,
        mobile: '',
        roleIds: [],
        userId: 0,
        username: '',
        address: '',
        status: 'normal',
        clientId: store.state.clientId,
        createTime: 0
      }
    }

    function handleCheckAllChange(index: number, vals: any) {
      // console.log(index, vals)

    }

    function onSelectAvatar(value: any) {
      console.log(value)
      data.AvatarsModal = false
    }

    onChangeApp(store.state.clientId)
    getAddressList()
    // 包装参数列表
    const refData = toRefs(data)
    return {
      ...refData,
      toRouter,
      handleDownload,
      hideDialog,
      onSelectAddress,
      whiteRow,
      deleteRow,
      getDataList,
      handleCurrentChange,
      handleSizeChange,
      onAddRow,
      onSubmit,
      onSelectRole,
      onChangeApp,
      resetPwd,
      onUpdataStatus,
      onChangeDialog,
      handleCheckAllChange,
      handleRadioChange,
      onSelectAvatar
    }
  },
  methods: {
    submitForm(formName: string) {
      const ref: any = this.$refs[formName]
      ref.validate((valid: string) => {
        if (valid) {
          this.onChangeDialog()
        } else {
          return false
        }
      })
    },
    resetForm(formName: string) {
      const ref: any = this.$refs[formName]
      ref.resetFields()
      this.hideDialog()
    }
  }
})
</script>
<style scoped>
  .el-from-style {
    margin-bottom: 1.875rem;
  }
</style>
